package com.hengxinguotong.zhihuichengjian.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.MyFragmentPagerAdapter;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.ui.MainActivity;
import com.hengxinguotong.zhihuichengjian.ui.WebViewActivity;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 资讯
 */
public class NewsFragment extends BaseFragment implements View.OnClickListener, ViewPager.OnPageChangeListener{

    private MainActivity mainActivity;
    private View rootView = null;

    @BindView(R.id.news_vp)
    ViewPager news_vp;
    @BindView(R.id.advertise_vp)
    ViewPager advertise_vp;
    @BindView(R.id.point_container)
    LinearLayout pointContainer;
    @BindView(R.id.bim_item)
    HXTextView bim_item;
    @BindView(R.id.zhgl_item)
    HXTextView zhgl_item;
    @BindView(R.id.hmcs_item)
    HXTextView hmcs_item;
    @BindView(R.id.cxjs_item)
    HXTextView cxjs_item;
    @BindView(R.id.slider)
    View slider;
    private int screenWidth ;
    private int currentpageItem ;

    private ChengxiangFragment FragmentCxjs,FragmentHmcs,FragmentZhgl,FragmentBim;
    private List<Fragment> fragments;
    private List<Integer> advertiseList;
    private List<ImageView> list;
    private Handler handler = new Handler();
    private int currentPage = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.news_fragment, null);
            ButterKnife.bind(this, rootView);
            mainActivity = (MainActivity) getActivity();
            initViewPager();
            initBottomLineWidth();
            initData();
            initAdvtiseVp();
            initPoints();
        }else {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    private void initData(){
        advertiseList = new ArrayList<>();
        advertiseList.add(R.mipmap.banner_news);
        advertiseList.add(R.mipmap.banner_news1);
    }

    private void initAdvtiseVp(){
        list = new ArrayList<ImageView>();
        for (int i = 0; i < advertiseList.size(); i++) {
            ImageView iv = new ImageView(getActivity());
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setImageResource(advertiseList.get(i));
            list.add(iv);
        }
        advertise_vp.setAdapter(new MyVPAdapter());
        advertise_vp.setCurrentItem(currentPage);
        advertise_vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPage = position;
                for (int i = 0; i < pointContainer.getChildCount(); i++) {
                    ImageView imageView = (ImageView) pointContainer.getChildAt(i);
                    if (i == position) {
                        imageView.setImageResource(R.mipmap.round);
                    } else {
                        imageView.setImageResource(R.mipmap.round_hui);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        new Handler().postDelayed(new MyRun(), 2000);
    }

    //初始化轮播图下的小圆点
    private void initPoints(){
        pointContainer.removeAllViews();
        for(int i=0; i<list.size(); i++){
            ImageView dot = new ImageView(mainActivity);
            if(i == currentPage){
                dot.setImageResource(R.mipmap.round);
            }else{
                dot.setImageResource(R.mipmap.round_hui);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout
                    .LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            if (i > 0) {
                params.leftMargin = 10;//设置圆点边距
            }
            dot.setLayoutParams(params);
            pointContainer.addView(dot);
        }
    }

    @Override
    public void onLazyLoad() {

    }

    //每隔2秒调度轮播图一次
    private class MyRun implements Runnable {

        @Override
        public void run() {
            int item = advertise_vp.getCurrentItem() + 1;
            advertise_vp.setCurrentItem(item);
            if (item == list.size()) {
                advertise_vp.setCurrentItem(0);
            }
            handler.postDelayed(new MyRun(), 2000);
        }
    }

    private void initViewPager(){
        fragments = new ArrayList<Fragment>();
        if(FragmentCxjs == null){
            FragmentCxjs = ChengxiangFragment.newInstance("cxjs");
        }
        fragments.add(FragmentCxjs);
        if(FragmentHmcs == null){
            FragmentHmcs = ChengxiangFragment.newInstance("hmcs");
        }
        fragments.add(FragmentHmcs);
        if(FragmentZhgl == null){
            FragmentZhgl = ChengxiangFragment.newInstance("zhgl");
        }
        fragments.add(FragmentZhgl);
        if(FragmentBim == null){
            FragmentBim = ChengxiangFragment.newInstance("bim");
        }
        fragments.add(FragmentBim);
        news_vp.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager(), fragments));
        news_vp.setCurrentItem(0);
        news_vp.addOnPageChangeListener(this);
    }

    @OnClick({R.id.cxjs_item, R.id.hmcs_item, R.id.zhgl_item, R.id.bim_item})
    public void onClick(View v) {
        clearState();
        switch (v.getId()){
            case R.id.cxjs_item:
                cxjs_item.setTextColor(getResources().getColor(R.color.main_color));
                news_vp.setCurrentItem(0);
                break;
            case R.id.hmcs_item:
                hmcs_item.setTextColor(getResources().getColor(R.color.main_color));
                news_vp.setCurrentItem(1);
                break;
            case R.id.zhgl_item:
                zhgl_item.setTextColor(getResources().getColor(R.color.main_color));
                news_vp.setCurrentItem(2);
                break;
            case R.id.bim_item:
                bim_item.setTextColor(getResources().getColor(R.color.main_color));
                news_vp.setCurrentItem(3);
                break;
        }
    }

    private void clearState(){
        cxjs_item.setTextColor(getResources().getColor(R.color.black));
        hmcs_item.setTextColor(getResources().getColor(R.color.black));
        zhgl_item.setTextColor(getResources().getColor(R.color.black));
        bim_item.setTextColor(getResources().getColor(R.color.black));
    }

    //初始化底部导航线的长度
    private void initBottomLineWidth()
    {
        DisplayMetrics me = new DisplayMetrics();
        mainActivity.getWindow().getWindowManager().getDefaultDisplay().getMetrics(me);
        //得到屏幕宽度的像素点
        screenWidth = me.widthPixels;
        //得到底部导航线的布局参数类对象
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) slider.getLayoutParams();
        //将宽度设置为屏幕宽度的1/4
        lp.width = screenWidth / 4;
        //将布局参数设置回slider
        slider.setLayoutParams(lp);
    }

    @Override
    public void onPageScrolled(int position, float offset, int positionOffsetPixels) {
        //得到bottom_line的LayoutParams参数对象
        LinearLayout.LayoutParams lp =(LinearLayout.LayoutParams) slider.getLayoutParams();
        int marginLeft = 0 ;
        if(currentpageItem == position)
        {
            marginLeft = (int)(currentpageItem*(screenWidth/4)+offset * (screenWidth/4));
            //为布局参数的左边距赋值
            lp.leftMargin = marginLeft ;
            slider.setLayoutParams(lp);
        }else
        {
            marginLeft = (int)(currentpageItem*(screenWidth/4) - ((1-offset) * (screenWidth/4)));
            lp.leftMargin = marginLeft ;
            slider.setLayoutParams(lp);
        }
    }

    @Override
    public void onPageSelected(int position) {
        clearState();
        switch (position){
            case 0:
                cxjs_item.setTextColor(getResources().getColor(R.color.main_color));
                break;
            case 1:
                hmcs_item.setTextColor(getResources().getColor(R.color.main_color));
                break;
            case 2:
                zhgl_item.setTextColor(getResources().getColor(R.color.main_color));
                break;
            case 3:
                bim_item.setTextColor(getResources().getColor(R.color.main_color));
                break;
        }
        currentpageItem = news_vp.getCurrentItem();
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private class MyVPAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return advertiseList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView img = list.get(position);
            container.addView(img);
            img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mainActivity, WebViewActivity.class);
                    intent.putExtra("title", "advertisement");
                    String url = null;
                    switch (position){
                        case 0:
                            url = "http://www.escst.com/app/zz/index.html";
                            break;
                        case 1:
                            url = "http://www.escst.com/app/cadb/index.html";
                            break;
                    }
                    intent.putExtra("url", url);
                    startActivity(intent);
                }
            });
            return img;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }
}
